import { reqGetCode, reqGetUserInfo, reqLayout, reqLogin, reqRegister } from "@/api"
import { setItem, getItem, clearItem } from '@/utils/token'
const state = {
    code: '',
    token: getItem(),
    userInfo: {}
}
const mutations = {
    GETCODE(state, data) {
        state.code = data
    },
    GETTOKEN(state, data) {
        state.token = data
    },
    GETUSER(state, data) {
        state.userInfo = data
    },
    CLEAR(state) {
        state.token = ''
        state.userInfo = {}
        clearItem()
    }
}
const actions = {
    async getCode({ commit }, phone) {
        console.log(phone);
        const res = await reqGetCode(phone)
        if (res.code === 200) {
            commit('GETCODE', res.data)
        }
    },
    async register({ commit }, user) {
        let res = await reqRegister(user)
        console.log(res)
        if (res.code == 200) {
            console.log(res.code)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));

        }
    },
    async login({ commit }, user) {
        let res = await reqLogin(user)
        if (res.code === 200) {
            commit('GETTOKEN', res.data.token)
            setItem(res.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async loginSucc({ commit }) {
        let res = await reqGetUserInfo()
        if (res.code === 200) {
            commit('GETUSER', res.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
    async layout({ commit }) {
        const res = await reqLayout()
        if (res.code = 200) {
            // 清除token等用户数据
            commit('CLEAR')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}